<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
import {useUserStore} from '@/stores/index.js'
import {customerBatchRemove, customerGetListService, customerUpdateStatusService} from "@/api/modules/customer.js";

defineOptions({name: 'customerManagement'})
const queryParams = ref({
  page: 1,
  size: 5,
  key: ''
})
const tableModel = ref([])
const total = ref('')
const getCustomerList = async () => {
  const {page, size, key} = queryParams.value
  const res = await customerGetListService(page, size, key)
  tableModel.value = res.records
  total.value = res.total
}

const handleSizeChange = async (event) => {
  queryParams.value.size = event
  await getCustomerList()
}

const handlePageChange = async (event) => {
  queryParams.value.page = event
  await getCustomerList()
}

const handleKeyChange = async (event) => {
  queryParams.value.key = event
}

const handleSearch = async () => {
  await getCustomerList()
}
onMounted(async () => {
  await getCustomerList()
})

const selectionIds = ref([])
const selectionChange = (event) => {
  selectionIds.value = event.map(item => item.id)
}
const batchRemove = async () => {
  await customerBatchRemove(selectionIds.value);
  await getCustomerList()
}

const handleCustomerStatus = async (id, isEnabled) => {
  await customerUpdateStatusService(id, isEnabled)
  await getCustomerList()
}

const baseUrl = import.meta.env.VITE_APP_BASE_API
const userStore = useUserStore()
const exportExcel = async () => {
  if (selectionIds.value.length === 0) {
    ElMessage.error('请勾选要导出的数据~')
    return
  }
  // 发送HTTP GET请求获取Excel文件流
  axios({
    url: `${baseUrl}/admin/customer/export`,
    method: 'POST',
    responseType: 'blob', // 重要
    data: selectionIds.value,
  }).then((response) => {
    // 创建一个Blob对象，内容为后端返回的文件流
    const blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});

    // 创建一个a标签，用于触发下载
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '客户表.xlsx'; // 下载文件的名称
    link.click();

    // 清理资源
    URL.revokeObjectURL(link.href);
  }).catch((error) => {
    console.error('下载失败:', error);
  });
}
</script>

<template>
  <el-card>
    <template #header>
      <div class="header">
        <div class="left">
          <el-button type="danger" @click="batchRemove" v-hasPerm="'biz:customer:dml'">删除勾选</el-button>
          <el-button type="primary" class="export" @click="exportExcel" v-hasPerm="'biz:customer:export'">导出Excel
          </el-button>
        </div>
        <div class="right">
          <el-input @input="handleKeyChange" @keyup.enter="handleSearch" prefix-icon="Search"
                    v-model="queryParams.key" class="input" placeholder="昵称/手机号" clearable
                    v-hasPerm="'biz:customer:dql'"></el-input>
          <el-button type="primary" @click="handleSearch" class="search" v-hasPerm="'biz:customer:dql'">查询
          </el-button>
        </div>
      </div>
    </template>
    <template #default>
      <el-table :data="tableModel" @selection-change="selectionChange" row-key="id">
        <el-table-column type="selection" reserve-selection show-overflow-tooltip v-hasPerm="'biz:customer:dml'"/>
        <el-table-column prop="id" label="id"></el-table-column>
        <el-table-column prop="avatar" label="头像" width="120">
          <template #default="{row}">
            <el-image :src="row.avatar" class="avatar"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称"/>
        <el-table-column prop="phone" label="手机号" width="120"/>
        <el-table-column prop="lastLoginTime" label="上次登录时间" sortable/>
        <el-table-column label="是否禁用" v-hasPerm="'biz:customer:dml'" width="120">
          <template #default="{row}">
            <el-switch
                v-model="row.isEnabled"
                class="ml-2"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                inline-prompt
                inactive-text="禁用"
                :inactive-value="0"
                active-text="启用"
                :active-value="1"
                @change="handleCustomerStatus(row.id,row.isEnabled)"
            />
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #footer>
      <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.size"
          :page-sizes="[5,10,15,20]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </template>
  </el-card>
</template>


<style lang="scss" scoped>
.el-card {
  padding: 0;
  height: 100%;

  :deep .el-card__header {
    height: 50px;
    padding: 10px;
  }

  :deep .el-card__body {
    height: calc(100% - 120px);
    padding: 10px;
  }
  :deep .el-card__footer {
    height: 50px;
    padding: 10px;
  }
  .el-table {
    height: calc(100%);
  }
}

.avatar {
  height: 50px;
  width: 50px;
  border-radius: 50%;
}

.header {
  display: flex;
  justify-content: space-between;

  .right {
    .search {
      margin: 0px 10px;
    }
  }

  .input {
    width: 150px;
  }
}
</style>
